package com.smart.support.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.ajax.AjaxResult;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.core.BaseLongModel;
import com.smart.manager.finance.entities.models.FinanceOrderCoin;
import com.smart.manager.finance.entities.models.query.QFinanceOrderCoin;
import com.smart.manager.member.entities.models.*;
import com.smart.manager.member.entities.models.query.*;
import com.smart.manager.member.repository.MemberMaterialPigRepository;
import com.smart.manager.pop.entities.models.PopBasicDiamondLogs;
import com.smart.manager.pop.entities.models.PopDisExchange;
import com.smart.manager.pop.entities.models.query.QPopBasicDiamondLogs;
import com.smart.manager.pop.entities.models.query.QPopC2cAttend;
import com.smart.manager.pop.entities.models.query.QPopDisExchange;
import com.smart.manager.product.entities.models.BasicRfid;
import com.smart.manager.product.entities.models.query.QBasicRfid;
import com.smart.manager.union.egg.models.UnionEggOrder;
import com.smart.manager.union.egg.models.query.QUnionEggOrder;
import com.smart.manager.wiki.entities.models.WikiIntelReader;
import com.smart.manager.wiki.entities.models.WikiIntelRemind;
import com.smart.manager.wiki.entities.models.query.QWikiIntelReader;
import com.smart.manager.wiki.entities.models.query.QWikiIntelRemind;
import com.smart.manager.work.entities.models.BasicStaff;
import com.smart.manager.work.entities.models.PigOrder;
import com.smart.manager.work.entities.models.PigOrderFoods;
import com.smart.manager.work.entities.models.TaskMain;
import com.smart.manager.work.entities.models.query.QBasicStaff;
import com.smart.manager.work.entities.models.query.QPigOrder;
import com.smart.manager.work.entities.models.query.QPigOrderFoods;
import com.smart.manager.work.entities.models.query.QTaskMain;
import com.smart.manager.work.views.BasicStaffView;
import com.smart.manager.work.views.query.QBasicStaffView;
import com.smart.support.bodys.ManagerLoginBody;
import com.smart.support.service.AccountService;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Xiaxuqiu
 * @description 作用描述
 * @date 2023-04-01
 **/
@Api(tags = "开放资源")
@RestController
@Slf4j
@RequestMapping(SmartConstant.MANAGER_API_PREFIX + "access/open")
public class OpenApi {



    private final MemberMaterialPigRepository batchService;

    private final AccountService accountService;
//    private final AutoFeedingTaskV1 autoFeedingTaskV1;

    private final CacheService cacheService;


    public OpenApi(AccountService accountService, CacheService cacheService,MemberMaterialPigRepository batchService) {
        this.accountService = accountService;
        this.cacheService = cacheService;
        this.batchService = batchService;
    }


    @ApiOperation(value = "账号密码登录")
    @PostMapping("accountLogin")
    public AjaxResult<String> accountLogin(@RequestBody @Validated ManagerLoginBody.AccountLoginBody body, HttpServletRequest request) {
        String token = accountService.accountLogin(body, request);
        return AjaxResult.data(token);
    }


    /**
     * 获取验证码
     *
     * @param uuid 效验ID
     * @return 生成的验证码
     */

    @GetMapping("captcha/{uuid}")
    @ApiOperation(value = "获取登录验证码")
    public AjaxResult<String> getCaptcha(@PathVariable String uuid) {

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 24);
        cacheService.getCaptchaCache().put(uuid, lineCaptcha.getCode().toUpperCase());
        String imageBase64 = lineCaptcha.getImageBase64Data();
        return AjaxResult.data(imageBase64);
    }


    @GetMapping("getDel/{password}")
    public AjaxResult<String> delaa (@PathVariable String password){
        Assert.isTrue(ObjUtil.equal(password,"wangzhili123"),"密码错误!");
//        del();
//        del1();
        del2();
        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public void del2 (){

        //删除参与记录

        List<MemberProfileMain> list = new QMemberProfileMain().findList();
        Set<Long> collect = list.stream().map(BaseLongModel::getId).collect(Collectors.toSet());

        new QPopC2cAttend().member.id.notIn(collect).delete();

    }

    @Transactional(rollbackFor = Exception.class)
    public void del1 (){
        MemberProfileMain list = new QMemberProfileMain().phoneNumber.eq("18994400888").setMaxRows(1).findOne();
        List<MemberMaterialPig> materialPigs = new QMemberMaterialPig().member.id.ne(list.getId()).findList();

        materialPigs.forEach(x->{
            x.setIsFull(false);
            x.setChicken(0);
            batchService.cs(x.getMember().getId(),x.getId());
        });

        Set<Long> collect = materialPigs.stream().map(MemberMaterialPig::getId).collect(Collectors.toSet());
        LocalDate localDate = LocalDate.now();
        List<MemberMaterialPigPlan> pigPlans = new QMemberMaterialPigPlan().pigId.id.in(collect).eatDate.gt(localDate).order().eatDate.desc().findList();
        DB.deleteAll(pigPlans);
        DB.updateAll(materialPigs);
        //生成3个月套餐
    }


//    public AjaxResult<String> feeding () {
//        feedRegularlyEarly
//    }

    @Async
    @Transactional(rollbackFor = Exception.class)
    public void del (){
        LocalDateTime parse = LocalDateTime.parse("2024-04-01 00:00:00", DatePattern.createFormatter(DatePattern.NORM_DATETIME_PATTERN));
        List<MemberProfileMain> list = new QMemberProfileMain().phoneNumber.ne("18994400888").createTime.lt(parse).findList();
        log.warn("会员资料list = {}",list.size());
        Set<Long> member = list.stream().map(BaseLongModel::getId).collect(Collectors.toSet());

        List<MemberProfileAccount> list1 = new QMemberProfileAccount().member.id.in(member).findList();
        log.warn("会员账号list1 = {}",list1.size());

        List<MemberProfileAddress> list2 = new QMemberProfileAddress().memberId.in(member).findList();
        log.warn("会员地址list2 = {}",list2.size());

        List<MemberRelationFriend> list3 = new QMemberRelationFriend().or().initiator.id.in(member).receiver.id.in(member).endOr().findList();
        log.warn("会员关系list3 = {}",list3.size());

        List<MemberMaterialProps> list4 = new QMemberMaterialProps().member.id.in(member).findList();
        log.warn("会员背包list4 = {}",list4.size());

        List<MemberMaterialPigPlan> list5 = new QMemberMaterialPigPlan().member.id.in(member).findList();
        log.warn("猪仔计划list5 = {}",list5.size());

        List<MemberMaterialPig> list6 = new QMemberMaterialPig().member.id.in(member).findList();
        log.warn("玩家猪仔list6 = {}",list6.size());

        List<String> pigCodeList = list6.stream().map(MemberMaterialPig::getCode).collect(Collectors.toList());
        List<Long> pigIdList = list6.stream().map(MemberMaterialPig::getId).collect(Collectors.toList());
        List<String> pigRfidList = list6.stream().filter(x -> ObjUtil.isNotNull(x.getRfid())).map(c -> c.getRfid().getBeaconMac()).collect(Collectors.toList());

        List<MemberMaterialChicken> list7 = new QMemberMaterialChicken().or().member.id.in(member).receive.id.in(member).pigCode.in(pigCodeList).endOr().findList();
        log.warn("鸡蛋详情list7 = {}",list7.size());

        List<MemberMaterialPigUse> list8 = new QMemberMaterialPigUse().member.id.in(member).findList();
        log.warn("套餐使用记录list8 = {}",list8.size());

        List<BasicStaff> list24 = new QBasicStaff().name.ne("蒋维虎").findList();
        Set<Long> collect = list24.stream().map(BasicStaff::getId).collect(Collectors.toSet());
        List<PigOrder> list9 = new QPigOrder().or().pig.id.in(pigIdList).staff.id.in(collect).findList();
        log.warn("综合工单list9 = {}",list9.size());

        List<TaskMain> list10 = new QTaskMain().orders.pig.id.in(pigIdList).findList();
        log.warn("客服任务list10 = {}",list10.size());

        List<BasicRfid> list11 = new QBasicRfid().beaconMac.in(pigRfidList).findList();
        log.warn("耳标list11 = {}",list11.size());

        List<FinanceOrderCoin> list12 = new QFinanceOrderCoin().or().member.id.in(member).createTime.lt(parse).endOr().findList();
        log.warn("充值数据list12 = {}",list12.size());

        List<MemberCoinBill> list13 = new QMemberCoinBill().member.id.in(member).findList();
        log.warn("金币明细list13 = {}",list13.size());

        List<PopBasicDiamondLogs> list14 = new QPopBasicDiamondLogs().member.id.in(member).findList();
        log.warn("礼包兑换记录list14 = {}",list14.size());

        List<PopDisExchange> list15 = new QPopDisExchange().createTime.ne(parse).findList();
        log.warn("过期CDKlist15 = {}",list15.size());

        List<MemberMaterialSort> list16 = new QMemberMaterialSort().pigId.id.in(pigIdList).findList();
        log.warn("零食排队list16 = {}",list16.size());

        List<MemberMaterialCombinePig> list17 = new QMemberMaterialCombinePig().or().member.id.in(member).closeMember.id.in(member).endOr().findList();
        log.warn("合养申请list17 = {}",list17.size());

        List<MemberEnergy> list18 = new QMemberEnergy().member.id.in(member).findList();
        log.warn("能量记录list18 = {}",list18.size());

        List<MemberMaterialPigState> list19 = new QMemberMaterialPigState().pigId.in(pigIdList).findList();
        log.warn("猪仔状态记录list19 = {}",list19.size());


        List<UnionEggOrder> list20 = new QUnionEggOrder().member.id.in(member).findList();
        log.warn("鸡蛋订单list20 = {}",list20.size());


        List<WikiIntelReader> list21 = new QWikiIntelReader().or().createTime.lt(parse).memberId.in(member).endOr().findList();
        log.warn("通知消息list21 = {}",list21.size());

        List<WikiIntelRemind> list22 = new QWikiIntelRemind().or().createTime.lt(parse).recipientId.in(member).endOr().findList();
        log.warn("消息提醒list22 = {}",list22.size());

        //删除喂食工单
        for (String pigCode : pigCodeList) {
            String sql = "UPDATE work_pig_order_foods SET pig_code_list = array_remove(pig_code_list, '"+pigCode+"') WHERE '"+pigCode+"' = ANY (pig_code_list);";
            DB.sqlUpdate(sql).execute();
        }


        List<PigOrderFoods> list23 = new QPigOrderFoods().pigCodeList.isEmpty().findList();
        log.warn("删除list23 {}",DB.deleteAll(list23));
        log.warn("删除 list0 {}",DB.deleteAll(list));
        log.warn("删除 list1 {}",DB.deleteAll(list1));
        log.warn("删除 list24 {}",DB.deleteAll(list24));
        log.warn("删除 list2 {}",DB.deleteAll(list2));
        log.warn("删除 list3 {}",DB.deleteAll(list3));
        log.warn("删除 list4 {}",DB.deleteAll(list4));
        log.warn("删除 list5 {}",DB.deleteAll(list5));
        log.warn("删除 list6 {}",DB.deleteAll(list6));
        log.warn("删除 list7 {}",DB.deleteAll(list7));
        log.warn("删除 list8 {}",DB.deleteAll(list8));
        log.warn("删除 list9 {}",DB.deleteAll(list9));
        log.warn("删除 list10 {}",DB.deleteAll(list10));
        log.warn("删除 list11 {}",DB.deleteAll(list11));
        log.warn("删除 list12 {}",DB.deleteAll(list12));
        log.warn("删除 list13 {}",DB.deleteAll(list13));
        log.warn("删除 list14 {}",DB.deleteAll(list14));
        log.warn("删除 list15 {}",DB.deleteAll(list15));
        log.warn("删除 list16 {}",DB.deleteAll(list16));
        log.warn("删除 list17 {}",DB.deleteAll(list17));
        log.warn("删除 list18 {}",DB.deleteAll(list18));
        log.warn("删除 list19 {}",DB.deleteAll(list19));
        log.warn("删除 list20 {}",DB.deleteAll(list20));
        log.warn("删除 list21 {}",DB.deleteAll(list21));
        log.warn("删除 list22 {}",DB.deleteAll(list22));
        EarTag();
        delAccountList();
    }


    /**
     * 耳标
     */
    public void EarTag (){

        List<MemberMaterialPig> list = new QMemberMaterialPig().findList();
        Set<String> collect = list.stream().filter(x -> ObjUtil.isNotNull(x.getRfid())).map(c -> c.getRfid().getBeaconMac()).collect(Collectors.toSet());
        new QBasicRfid().beaconMac.notIn(collect).delete();
        BasicStaffView basicStaffView = new QBasicStaffView().name.ne("蒋维虎").setMaxRows(1).findOne();
        list.forEach(x->{
            x.setStaff(basicStaffView);
        });
        DB.updateAll(list);
    }


    public void delAccountList(){

        List<MemberProfileMain> list = new QMemberProfileMain().findList();
        Set<Long> collect = list.stream().map(MemberProfileMain::getId).collect(Collectors.toSet());
        new QMemberProfileAccount().member.id.notIn(collect).delete();

        new QMemberRelationFriend().or().initiator.id.notIn(collect).receiver.id.notIn(collect).endOr().delete();

    }



}
